package grape.wx.rest.mp.basic.mvc;

import grape.common.exception.ExceptionTools;
import grape.common.rest.advice.DisableGRB;
import grape.common.rest.advice.DisableGRM;
import grape.common.rest.mvc.SuperController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * Created by yangwei
 * Created at 2020/7/20 20:48
 */
@Slf4j
@RestController
@RequestMapping("/wx/mp/portal/{appId}")
@Api(tags = "公众号对接入口相关接口")
@DisableGRB
@DisableGRM
public class MpPortalController extends SuperController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpMessageRouter messageRouter;

    @ApiOperation("接收来自微信的推送")
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId,
                       @RequestBody String requestBody,
                       String signature,
                       String timestamp,
                       String nonce,
                       String openId,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        this.wxMpService.switchover(appId);

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw ExceptionTools.invalidParamsRE("不合法的参数");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("消息解密后内容为：{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        log.debug("组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

    @ApiOperation("验证请求来自微信")
    @GetMapping(produces = "text/plain;charset=utf-8")
    @ResponseStatus(HttpStatus.OK)
    public String validate(@PathVariable String appId,
                          String signature,
                          String timestamp,
                          String nonce,
                          String echostr) {

        this.wxMpService.switchover(appId);

        return wxMpService.checkSignature(timestamp, nonce, signature) ? echostr: null;
    }
}
